<template>
	<view class="recommend-page">
		<view class="toolbar">
			<button size="mini" class="tool-btn refresh-btn" @click="refresh"><text class="icon">⟳</text><text>换一批</text></button>
			<button size="mini" class="tool-btn filter-btn" @click="openFilter"><text class="icon">🔍</text><text>筛选</text></button>
		</view>
		<uni-popup ref="filterPopup" type="bottom" :mask-click="true">
			<view class="filter-sheet">
				<view class="sheet-handle"></view>
				<view class="sheet-title">精确筛选</view>
				<view class="sheet-body">
					<view class="field">
						<text class="field-label">性别</text>
						<view class="seg">
							<view :class="['seg-item', query.gender===null?'active':'']" @click="setGender(null)">不限</view>
							<view :class="['seg-item', query.gender===1?'active':'']" @click="setGender(1)">男</view>
							<view :class="['seg-item', query.gender===2?'active':'']" @click="setGender(2)">女</view>
						</view>
					</view>
					<view class="field two">
						<text class="field-label">年龄</text>
						<input class="ipt" type="number" v-model.number="query.ageMin" placeholder="最小" />
						<text class="dash">-</text>
						<input class="ipt" type="number" v-model.number="query.ageMax" placeholder="最大" />
					</view>
					<view class="field two">
						<text class="field-label">身高(cm)</text>
						<input class="ipt" type="number" v-model.number="query.heightMin" placeholder="最小" />
						<text class="dash">-</text>
						<input class="ipt" type="number" v-model.number="query.heightMax" placeholder="最大" />
					</view>
					<view class="field">
						<text class="field-label">城市</text>
						<picker mode="selector" :range="cityList" range-key="name" @change="onCityChange">
							<view class="ipt full picker">{{ currentCityName || '选择城市' }}</view>
						</picker>
						<picker mode="selector" :range="areaList" range-key="name" @change="onAreaChange" v-if="areaList.length">
							<view class="ipt full picker">{{ currentAreaName || '选择区域' }}</view>
						</picker>
					</view>
					<view class="field two">
						<text class="field-label">学历/收入</text>
						<picker mode="selector" :range="educationOptions" range-key="label" @change="onEduChange">
							<view class="ipt picker">{{ currentEduText || '不限学历' }}</view>
						</picker>
						<picker mode="selector" :range="salaryOptions" range-key="label" @change="onSalaryChange">
							<view class="ipt picker">{{ currentSalaryText || '不限收入' }}</view>
						</picker>
					</view>
					<view class="field two">
						<text class="field-label">星座/生肖</text>
						<picker mode="selector" :range="starOptions" range-key="label" @change="onStarChange">
							<view class="ipt picker">{{ currentStarText || '不限星座' }}</view>
						</picker>
						<picker mode="selector" :range="animalOptions" range-key="label" @change="onAnimalChange">
							<view class="ipt picker">{{ currentAnimalText || '不限生肖' }}</view>
						</picker>
					</view>
					<view class="field">
						<text class="field-label">兴趣</text>
						<input class="ipt full" v-model="hobbyInput" placeholder="用逗号分隔，如：旅行,音乐" />
					</view>
				</view>
				<view class="sheet-actions">
					<button class="btn ghost" @click="resetFilter">重置</button>
					<button class="btn primary" @click="applyFilter">确定</button>
				</view>
			</view>
		</uni-popup>
		<scroll-view scroll-y class="list">
			<view v-if="loading" class="skeleton">加载中...</view>
			<view v-else>
				<view v-for="(u, idx) in list" :key="u.userId || idx" class="card">
					<image :src="u.avatarUrl || '/static/close.png'" class="avatar" mode="aspectFill" @error="onImgErr(idx)"/>
					<view class="main">
						<view class="row">
							<text class="name">{{ u.nickname || '-' }}</text>
							<text class="score-badge">{{ fmtScore(u.compatibilityScore) }}</text>
						</view>
						<view class="meta">
							<text>{{ fmtGender(u.gender) }}</text>
							<text v-if="u.height">{{ u.height }}cm</text>
							<text v-if="u.educationLevel">{{ fmtEdu(u.educationLevel) }}</text>
							<text v-if="u.salaryRange">{{ fmtSalary(u.salaryRange) }}</text>
						</view>
						<view class="tags">
							<text v-if="u.star" class="tag">{{ u.star }}</text>
							<text v-if="u.animal" class="tag">{{ u.animal }}</text>
							<text v-if="u.jobTitle" class="tag">{{ u.jobTitle }}</text>
							<text v-for="t in parseHobby(u.hobby)" :key="t" class="tag">{{ t }}</text>
						</view>
					</view>
					<view class="actions">
						<button size="mini" class="act-btn ghost" @click="dislike(idx)">不喜欢</button>
						<button size="mini" class="act-btn primary" @click="like(idx)">喜欢</button>
					</view>
				</view>
				<view v-if="!list.length" class="empty">暂无推荐</view>
			</view>
		</scroll-view>
		<!-- 底部导航栏 -->
		<view class="tabbar">
			<view class="tabbar-item" @click="switchTab('index')">
				<text class="tabbar-icon">🏠</text>
				<text class="tabbar-text">首页</text>
			</view>
			<view class="tabbar-item" @click="switchTab('plaza')">
				<text class="tabbar-icon">💕</text>
				<text class="tabbar-text">广场</text>
			</view>
			<view class="tabbar-item active" @click="switchTab('recommend')">
				<text class="tabbar-icon">👍</text>
				<text class="tabbar-text">推荐</text>
			</view>
			<view class="tabbar-item" @click="switchTab('message')">
				<text class="tabbar-icon">💬</text>
				<text class="tabbar-text">消息</text>
			</view>
			<view class="tabbar-item" @click="switchTab('mine')">
				<text class="tabbar-icon">👤</text>
				<text class="tabbar-text">我的</text>
			</view>
		</view>
	</view>
</template>

<script>
import api from '@/utils/api.js'
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
export default {
  components: { uniPopup },
	data() {
		return { list: [], loading: false, oppoOnly: 1,
		  query: { userId: null, gender: null, ageMin: null, ageMax: null, heightMin: null, heightMax: null, cityId: null, areaId: null, educationMin: null, salaryMin: null, star: null, animal: null, hobbyTags: [], limit: 20, offset: 0 },
      hobbyInput: '',
      genderOptions: [{label:'不限', value:null},{label:'男', value:1},{label:'女', value:2}],
      educationOptions: [
        {label:'不限', value:null},{label:'高中及以下', value:1},{label:'大专', value:2},{label:'本科', value:3},{label:'硕士', value:4},{label:'博士', value:5}
      ],
      salaryOptions: [
        {label:'不限', value:null},{label:'<5k', value:1},{label:'5-10k', value:2},{label:'10-20k', value:3},{label:'20-50k', value:4},{label:'50k+', value:5}
      ],
		  starOptions: [
		    {label:'不限', value:null},{label:'白羊座', value:'白羊座'},{label:'金牛座', value:'金牛座'},{label:'双子座', value:'双子座'},{label:'巨蟹座', value:'巨蟹座'},{label:'狮子座', value:'狮子座'},{label:'处女座', value:'处女座'},{label:'天秤座', value:'天秤座'},{label:'天蝎座', value:'天蝎座'},{label:'射手座', value:'射手座'},{label:'摩羯座', value:'摩羯座'},{label:'水瓶座', value:'水瓶座'},{label:'双鱼座', value:'双鱼座'}
		  ],
		  animalOptions: [
		    {label:'不限', value:null},{label:'鼠', value:'鼠'},{label:'牛', value:'牛'},{label:'虎', value:'虎'},{label:'兔', value:'兔'},{label:'龙', value:'龙'},{label:'蛇', value:'蛇'},{label:'马', value:'马'},{label:'羊', value:'羊'},{label:'猴', value:'猴'},{label:'鸡', value:'鸡'},{label:'狗', value:'狗'},{label:'猪', value:'猪'}
		  ],
		  currentEduText: '', currentSalaryText: '', currentStarText: '', currentAnimalText: '',
      provinceList: [], cityList: [], areaList: [], currentProvinceName: '', currentCityName: '', currentAreaName: ''
    }
	},
	onLoad() { this.refresh() },
	methods: {
		switchTab(tab) {
			if (tab === 'recommend') return
			const tabPages = {
				index: '/pages/index/index',
				plaza: '/pages/plaza/index',
				message: '/pages/message/index',
				mine: '/pages/mine/index'
			}
			if (tabPages[tab]) {
				uni.redirectTo({ url: tabPages[tab] })
			}
		},
    async refresh() {
			this.loading = true
			try {
        const storedUserId = uni.getStorageSync('userId'); const userId = storedUserId ? parseInt(storedUserId) : 1
        // 如果没有筛选，走默认接口；有筛选，调用 search
        if (!this.hasFilter()) {
          const data = await api.recommend.getUsers({ userId, oppoOnly: this.oppoOnly, limit: 20 })
          const seen = new Set(); const merged = []
          for (const it of (data || [])) { if (!seen.has(it.userId)) { seen.add(it.userId); merged.push(it) } }
          this.list = merged.map(it=>({ ...it, avatarUrl: this.getSafeAvatar(it.avatarUrl) }))
        } else {
          this.query.userId = userId; this.query.limit = 20; this.query.offset = 0
          const payload = this.buildQueryPayload()
          const data = await api.recommend.search(payload)
          const arr = Array.isArray(data) ? data : []
          this.list = arr.map(it=>({ ...it, avatarUrl: this.getSafeAvatar(it.avatarUrl) }))
        }
			} catch (e) {
        const msg = (e && (e.message || e.msg)) ? String(e.message || e.msg) : '获取推荐失败'
        console.error('recommend/search error:', e)
        uni.showToast({ title: msg, icon: 'none' })
			} finally { this.loading = false }
		},
    openFilter(){ this.ensureAreaData(); this.$refs.filterPopup.open('bottom') },
    closeFilter(){ this.$refs.filterPopup.close() },
    applyFilter(){ this.$refs.filterPopup.close(); this.refresh() },
		hasFilter(){
		  const q=this.query
		  return !!(q.gender||q.ageMin||q.ageMax||q.heightMin||q.heightMax||q.cityId||q.areaId||q.educationMin||q.salaryMin||q.star||q.animal||this.hobbyInput)
		},
    genderText(v){ if(v===1)return '男'; if(v===2)return '女'; return '不限' },
    setGender(v){ this.query.gender=v },
    onEduChange(e){
      const item = this.educationOptions[e.detail.value];
      this.query.educationMin = item.value;
      this.currentEduText = item.label;
    },
    onSalaryChange(e){
      const item = this.salaryOptions[e.detail.value];
      this.query.salaryMin = item.value;
      this.currentSalaryText = item.label;
    },
		onStarChange(e){
		  const item = this.starOptions[e.detail.value];
		  this.query.star = item.value || null;
		  this.currentStarText = item.label;
		},
		onAnimalChange(e){
		  const item = this.animalOptions[e.detail.value];
		  this.query.animal = item.value || null;
		  this.currentAnimalText = item.label;
		},
    buildQueryPayload(){
      const q = { ...this.query };
      if (this.hobbyInput) {
        q.hobbyTags = this.hobbyInput.split(',').map(s=>s.trim()).filter(Boolean)
      } else {
        delete q.hobbyTags
      }
      // 清理空值/空字符串/NaN，避免后端收到无效条件
      Object.keys(q).forEach(k => {
        const v = q[k];
        if (v === null || v === undefined || v === '' || (typeof v === 'number' && Number.isNaN(v))) {
          delete q[k]
        }
      })
      return q
    },
		resetFilter(){
		  this.query={...this.query, gender:null, ageMin:null, ageMax:null, heightMin:null, heightMax:null, cityId:null, areaId:null, educationMin:null, salaryMin:null, star:null, animal:null};
		  this.hobbyInput=''; this.currentCityName=''; this.currentAreaName=''; this.currentStarText=''; this.currentAnimalText=''; this.areaList=[]
		},
    async ensureAreaData(){
      // 无省份，直接加载热门城市或全量城市
      if(!this.cityList.length){
        try{ this.cityList = await api.area.getCities() }catch(e){}
      }
    },
    async onCityChange(e){
      const idx = e.detail.value; const c = this.cityList[idx]
      this.currentCityName = c?.name || ''
      this.query.cityId = c?.id || null
      this.currentAreaName = ''
      this.areaList = []
      if(this.query.cityId){
        try{ this.areaList = await api.area.getAreas(this.query.cityId) }catch(err){}
      }
    },
    onAreaChange(e){
      const idx = e.detail.value; const a = this.areaList[idx]
      this.currentAreaName = a?.name || ''
      this.query.areaId = a?.id || null
    },
    getSafeAvatar(url){
      if(!url) return '/static/close.png'
      const u = String(url)
      if(u.includes('example.com')) return '/static/close.png'
      return u
    },
		fmtScore(s){ return s ? Number(s).toFixed(1) : '0.0' },
		fmtGender(g){ return g===1?'男':g===2?'女':'-' },
		fmtEdu(v){ const map={1:'高中',2:'大专',3:'本科',4:'硕士',5:'博士'}; return map[v]||'-' },
		fmtSalary(v){ const map={1:'<5k',2:'5-10k',3:'10-20k',4:'20-50k',5:'50k+'}; return map[v]||'-' },
		parseHobby(h){ try{ const arr = typeof h === 'string' ? JSON.parse(h) : h; return Array.isArray(arr)?arr.slice(0,6):[] }catch{return []} },
		async like(i){ 
			const u=this.list[i]; 
			if(!u) return; 
			
			const uid = parseInt(uni.getStorageSync('userId')||1); 
			
			// 调用 API 记录喜欢
			if(u.userId){ 
				try {
					await api.recommend.feedback({ userId: uid, targetUserId: u.userId, type: 'like' });
				} catch(e) {
					console.error('反馈失败', e);
				}
			}
			
			// 显示选择弹窗
			uni.showModal({
				title: '已喜欢 ❤️',
				content: `你喜欢了 ${u.nickname || '该用户'}，要立即发消息吗？`,
				confirmText: '发消息',
				cancelText: '继续浏览',
				success: (res) => {
					if (res.confirm) {
						// 跳转到聊天页面
						this.openChat(u);
					} else {
						// 继续浏览，显示成功提示
						uni.showToast({ title:'已记录', icon:'success' });
					}
				}
			});
		},
		
	openChat(user) {
		// 验证必要参数
		if (!user || !user.userId) {
			uni.showToast({
				title: '用户信息错误',
				icon: 'none'
			});
			return;
		}
		
		// 跳转到聊天页面
		const targetUserId = parseInt(user.userId);
		const targetUserName = user.nickname || '用户';
		const targetUserAvatar = user.avatarUrl || '/static/close.png';
		
		console.log('跳转到聊天页面，参数：', {
			targetUserId,
			targetUserName,
			targetUserAvatar
		});
		
		uni.navigateTo({
			url: `/pages/message/chat?targetUserId=${targetUserId}&targetUserName=${encodeURIComponent(targetUserName)}&targetUserAvatar=${encodeURIComponent(targetUserAvatar)}`
		});
	},
		dislike(i){ const u=this.list[i]; if(!u) return; this.list.splice(i,1); uni.showToast({ title:'已隐藏', icon:'none' });
			const uid = parseInt(uni.getStorageSync('userId')||1); if(u.userId){ api.recommend.feedback({ userId: uid, targetUserId: u.userId, type: 'dislike' }) } },
		onImgErr(idx){ this.$set(this.list[idx], 'avatarUrl', '/static/close.png') }
	}
}
</script>

<style lang="scss" scoped>
	.recommend-page { min-height: 100vh; background-color: #FFF9F9; padding-bottom: 120rpx; }
	.toolbar{ display:flex; justify-content:space-between; align-items:center; padding:16rpx 20rpx; }
	.tool-text{ font-size:26rpx; color:#666 }
	.tool-btn{ height:64rpx; padding:0 24rpx; border-radius:999rpx; display:flex; align-items:center; gap:10rpx; font-size:26rpx; background:#fff; border:2rpx solid #eee; box-shadow:0 8rpx 20rpx rgba(0,0,0,.04); color:#333 }
	.tool-btn .icon{ font-size:28rpx }
	.refresh-btn{ background:#FFE5EE; border-color:#FFD6E6; color:#D81B60 }
	.filter-btn{ background:#ffffff; border-color:#eeeeee; color:#333 }
	.list{ height: calc(100vh - 260rpx); padding: 0 20rpx }
	.skeleton{ padding:40rpx; text-align:center; color:#999 }
	.empty{ padding:60rpx 20rpx; text-align:center; color:#999; font-size:26rpx }
	.card{ display:flex; background:#fff; border-radius:16rpx; padding:20rpx; margin:16rpx 0; box-shadow:0 4rpx 12rpx rgba(0,0,0,.05) }
	.avatar{ width:140rpx; height:140rpx; border-radius:12rpx; background:#f5f5f5 }
	.main{ flex:1; padding:0 16rpx }
	.row{ display:flex; align-items:center; justify-content:space-between }
	.name{ font-size:32rpx; font-weight:600; color:#333 }
	.score{ font-size:28rpx; color:#E91E63 }
	.score-badge{ min-width: 80rpx; text-align:center; padding: 6rpx 16rpx; border-radius:999rpx; background:#FFE5EE; color:#D81B60; font-size:26rpx; font-weight:600 }
	.meta{ display:flex; gap:16rpx; font-size:24rpx; color:#666; margin-top:8rpx }
	.tags{ display:flex; flex-wrap:wrap; gap:10rpx; margin-top:10rpx }
	.tag{ background:#FFF0F5; color:#E91E63; padding:6rpx 12rpx; border-radius:999rpx; font-size:22rpx }
	.actions{ display:flex; flex-direction:column; gap:10rpx; justify-content:center }
	.act-btn{ border-radius:999rpx; padding: 0 20rpx; height: 56rpx; line-height:56rpx; font-size:24rpx }
	.act-btn.ghost{ background:#f7f7f7; color:#666 }
	.act-btn.primary{ background:#E91E63; color:#fff }

	/* 底部导航栏 */
	.tabbar { position: fixed; bottom: 0; left: 0; right: 0; display: flex; background-color: #FFFFFF; border-top: 1rpx solid #F0F0F0; padding-bottom: constant(safe-area-inset-bottom); padding-bottom: env(safe-area-inset-bottom); z-index: 999; }
	.tabbar-item { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 15rpx 0; }
	.tabbar-icon { font-size: 44rpx; margin-bottom: 5rpx; }
	.tabbar-text { font-size: 22rpx; color: #666666; }
	.tabbar-item.active .tabbar-text { color: #E91E63; font-weight: bold; }

	/* 美化筛选抽屉 */
	.filter-sheet{ background:#fff; border-top-left-radius:24rpx; border-top-right-radius:24rpx; padding-bottom: env(safe-area-inset-bottom); }
	.sheet-handle{ width: 120rpx; height: 10rpx; background:#eaeaea; border-radius:5rpx; margin: 16rpx auto; }
	.sheet-title{ text-align:center; font-size:32rpx; font-weight:600; color:#333; margin-bottom: 10rpx; }
	.sheet-body{ padding: 0 28rpx 20rpx; max-height: 60vh; overflow:auto; }
	.field{ margin: 18rpx 0; }
	.field.two{ display:flex; align-items:center; }
	.field-label{ width: 160rpx; color:#666; font-size:26rpx; }
	.ipt{ flex:1; height: 70rpx; line-height:70rpx; background:#f7f7f7; border-radius:12rpx; padding: 0 20rpx; margin-right: 12rpx; font-size:26rpx; display:flex; align-items:center; }
	.ipt.full{ width: 100%; margin-right:0; }
	.dash{ color:#bbb; margin-right:12rpx; }
	.seg{ display:flex; gap:14rpx; }
	.seg-item{ flex:1; text-align:center; padding: 14rpx 0; border-radius:999rpx; background:#f7f7f7; color:#666; font-size:26rpx; }
	.seg-item.active{ background:#FFE5EE; color:#E91E63; font-weight:600; }
	.sheet-actions{ display:flex; gap:16rpx; padding: 12rpx 28rpx 28rpx; }
	.btn{ flex:1; height: 80rpx; border-radius:999rpx; display:flex; align-items:center; justify-content:center; font-size:28rpx; }
	.btn.ghost{ background:#f7f7f7; color:#666 }
	.btn.primary{ background:#E91E63; color:#fff }
</style>

